package com.opensky.qatest.util.selenium;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

import com.opensky.qatest.util.common.Properties;

public class Screenshot {

    private static final Logger LOGGER = Logger.getLogger(Screenshot.class);

    private static final String USER_DIR = "user.dir";

    private static final String SCREENSHOT_DIR = "screenshot.dir";

    private static final String SCREENSHOT_LINK = "<a href='../../../%s/%s'>Open screenshot</a>";

    public static String take(String elementName, WebDriver driver) {

	String directory = String.format("%s/%s", System.getProperty(USER_DIR), Properties.get(SCREENSHOT_DIR));
	File screenDir = new File(directory);

	if (!screenDir.exists()) {
	    screenDir.mkdir();
	}

	String screenName = String.format("%s-%d.png", elementName, System.currentTimeMillis());
	String screenPath = String.format("%s/%s", screenDir.getAbsolutePath(), screenName);
	File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

	try {
	    FileUtils.copyFile(screenshot, new File(screenPath));
	} catch (IOException e) {
	    LOGGER.error("Problems with screenshot capturing!");
	    return "";
	}
	return String.format(SCREENSHOT_LINK, Properties.get(SCREENSHOT_DIR), screenName);
    }
}
